package de.jmda.common.ui.web.vaadin.service;

import javax.ejb.EJB;

import com.google.common.eventbus.EventBus;

import de.jmda.home.bl.usermgmt.UserManagementBean;

public class DefaultSessionContext
    extends AbstractSessionContext
{
	/**
	 * event bus for loosely coupled component communication
	 */
	private EventBus eventBus = new EventBus();
	
	/**
	 * TODO make use of CDI as soon as possible, i. e. remove this field
	 */
	@EJB
	private UserManagementBean userManagement;

	/**
	 * name of authenticated user, <code>null</code> if no authenticated
	 * user is logged in for the current session
	 */
	private String username;

	public DefaultSessionContext()
	{
		super();
	}

	/**
	 * @return see {@link #eventBus}
	 */
	public EventBus getEventBus()
	{
		return eventBus;
	}
	
	/**
	 * @return {@link #username}
	 */
	public String getUsername()
	{
		return username;
	}
	
	/**
	 * @param username see {@link #username}
	 */
	public void setUsername(String username)
	{
		this.username = username;
	}

	public UserManagementBean getUserManagement()
	{
		if (userManagement == null)
		{
			throw new IllegalStateException("userManagement must not be null");
		}

		return userManagement;
	}

	public void setUserManagement(UserManagementBean userManagement)
	{
		if (userManagement == null)
		{
			throw new IllegalArgumentException("userManagement must not be null");
		}

		this.userManagement = userManagement;
	}

	public static DefaultSessionContext get()
	{
		Object result = AbstractSessionContext.get();
		
		if (result == null)
		{
			throw new IllegalStateException("no default session context data");
		}
		
		if (false == (result instanceof DefaultSessionContext))
		{
			throw new IllegalStateException(
					"wrong type of default session context data: " +
			result.getClass().getName());
		}

		return (DefaultSessionContext) result;
	}
}